'''
Descripttion: 
version: 
Author: dylan.Ding
Date: 2020-12-02 19:17:24
LastEditors: Please set LastEditors
LastEditTime: 2021-04-21 17:08:01
'''
import numpy as np
import re
import os
import linecache
import configparser
import paramiko
from sklearn import linear_model
from sklearn.metrics import mean_squared_error as MSE
from sklearn.preprocessing import StandardScaler

# client: transform the data it receive to it could understand
def handleReceive(data, begin=4, end=-1):
    data = str(data)
    matchstr = r'[\[+\]+\'+,+\s+]'
    result = re.split(matchstr, data)
    result = [item for item in filter(lambda x: x != '', result)]
    sorce_list = result[0:begin]
    sorce_list = [float(item) for item in sorce_list]
    tool = result[end]
    register_result_list = result[begin:end]
    return tool, sorce_list, register_result_list


# transform the data it receive to it could understand
# def handleReceive(data, begin=4, end=-1):
#     sorce_list = data[0:begin]
#     sorce_list = [float(item) for item in sorce_list]
#     tool = data[end]
#     register_result_list = data[begin:end]
#     return tool, sorce_list, register_result_list


# client: transform the data it send to the server could understand
# def handleSend(data):
#     result = "set"
#     for item in data:
#         result = result + str(item) + ','
#     result = result[0:-1]
#     return result


# Judge whether the server is break
def isDangError(data):
    if data == ['DownError']:
        return True
    return False

# Judge whether stream test timeout
def isTimeoutError(data):
    if data == ['TimeoutError']:
        return True
    return False


# Judge whether the server is break when run shell
def isRunError(data):
    if data == ['runshellerror']:
        return True
    return False


# Get the score from files when the action appears before
def getScoreFromFile(score_file, index):
    linecache.checkcache(score_file)
    theline = linecache.getline(score_file, index+1)
    matchstr = r'[,+\n]'
    result = re.split(matchstr, theline)
    result = [float(item) for item in filter(lambda x: x != '', result)]
    linecache.clearcache()
    return result


# Read file
def readFile(filename):
    result_list = []
    with open(filename, 'r') as f:
        while True:
            line = f.readline()
            if not line:
                break
                pass
            # handle the whole line datas and drop '\n' in the end
            line = line.replace(',', '')
            line = line[:-1]
            result_list.append(line)
    return result_list


# Write an item
def writeFile(filename, ways, data):
    result = actionToWrite(data)
    # add '\n' in the end to become a line
    result = result + '\n'
    with open(filename,  ways) as f:
        f.writelines(result)


# When the server break, ping IP until it restart
def pingIP(serverIp):
    backinfo = os.system('ping -w 2 %s' % serverIp)
    if backinfo:
        return False
    return True


# Judge the ssh connect is ok
def sshConnect(ip, port, user, passward):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # build connect
        ssh.connect(ip, port, user, passward, timeout=10)
        # # test
        # stdin, stdout, stderr = ssh.exec_command("pwd")
        # result = stdout.read()
        # print(result)
        ssh.close()
        return True
    except Exception:
        return False


# transform the action to writing format
def actionToWrite(data):
    result = ''
    for item in data:
        result = result + str(item)+","
    result = result[:-1]
    return result


# Transform the action to a string for appending in the list
def listToStr(data):
    result = ''
    for item in data:
        result = result + str(item)
    return result


def changeBiosFormat(bios_data):
    # print(bios_data)
    matchstr = r'[\[+\]+,+\s+]'
    bios_data = re.split(matchstr, bios_data)
    bios_data = [int(item) for item in filter(lambda x: x != '', bios_data)]
    return bios_data


# compute the variance and slope
def computeLine(y):
    x = []
    y = np.array(y).reshape(-1, 1)
    for index, _ in enumerate(y):
            x.append([index])
    scaler = StandardScaler()
    scaler.fit(y)
    y = scaler.transform(y)

    reg = linear_model.LinearRegression()
    reg.fit(x, y)
    k = float(np.squeeze(reg.coef_))
    y_pred = reg.predict(x)
    mse = MSE(y_pred, y)
    mse = np.sqrt(mse)
    return k, mse


# create file
def createFile(filename):
    if not os.path.exists(filename):
        fd = open(filename, mode="w", encoding="utf-8")
        fd.close()
        return True
    return False


if __name__ == "__main__":
    # data = "['236750.4']['231326.8']['230587.1']['231720.6']['success']['success']['success']['success']['success']['success']['success']['success']['success']['success']['success']['success']['success']['success']['success']['success']['success']['success']['success']['success']['stream']]"
    # list1 = [1 for x in range(64)]
    # print(handleReceive(data, 4, -1))
    # print(handleSend(list1))
    black_file = '/home/dingqy/VVVBIOS/code/black.txt'
    list1 = ['1' for x in range(64)]
    print(list1)
    for i in range(10):
        writeFile(black_file, 'a', [1, 2, 3, 4])
    writeFile(black_file, 'a', [1, 2, 3, 4])

    print(readFile(black_file))
    print(pingIP('127.0.0.1111'))

    sshConnect("127.0.0.1", 22, "1", "!2")

    createFile("/home/dingqy/VVVBIOS/code/score.txt")
